import { ChangeEvent, useEffect, useState } from 'react'
import style from './login.module.scss'
import "./login.less"
import initCanvasBg from './init'
import { Input, Button, Space, message,Col, Row } from 'antd';
import { getCaptchaApi,delCaptchaApi } from '@/api/user/user';
import { useNavigate } from 'react-router-dom';
import useStore from '@/store/index'
import { UserOutlined, LockOutlined } from '@ant-design/icons';
const Login = () => {


  // 加载完这个组件之后，加载背景
  useEffect(() => {
    initCanvasBg();
    window.onresize = function () { initCanvasBg() };
    upCaptcha()
  }, [])
  const NavigateTo = useNavigate()
  // 获取用户输入的信息
  const [usernameValue, setUsernameVal] = useState("")
  // 获取用户输入的信息
  const [pwdValue, setPwdVal] = useState("")
  // 获取验证码输入的信息
  const [captchaValue, setCaptchaVal] = useState("")
  // 验证码图片信息
  const [captchaImg, setCaptchaImg] = useState("")
  // 验证码text信息
  const [captchaText, setCaptchaText] = useState("")
  const clogin = useStore((state:any)=>state.login)

  // 响应式用户名
  const usernameChange = (e: ChangeEvent<HTMLInputElement>) =>  setUsernameVal(e.target.value)
  
  // 响应式密码
  const pwdChange = (e: ChangeEvent<HTMLInputElement>) => setPwdVal(e.target.value)
  
  // 响应式验证码
  const captchaChange = (e: ChangeEvent<HTMLInputElement>) => setCaptchaVal(e.target.value)


  
  // 更新获取验证码
  const upCaptcha = async () => {
    const captchaToken = localStorage.getItem('captchaToken') 
    if(captchaToken){
      const captchaParams = {
        'captchaToken':captchaToken  as string
      }
      await delCaptchaApi(captchaParams)
    }
    let res: CaptchaApiRes = await getCaptchaApi()
    // 获取成功
    if (res.code == 200) {
      // 赋值验证码图片信息和text信息
      setCaptchaImg(res.captcha.data)
      setCaptchaText(res.captcha.text)
      // 本地存储captchaToken
      localStorage.setItem('captchaToken', res.captcha.captchaToken)
    }
  }
  // 登录按钮
  const loginBtn = async () => {
    // 判断用户是否输入了信息
    if (!usernameValue.trim()) {
      message.open({
        type: 'warning',
        content: '请输入用户名',
        duration: 2.5,
      });
      return
    }else if(!pwdValue.trim()){
      message.open({
        type: 'warning',
        content: '请输入密码',
        duration: 2.5,
      });
    }else if(!captchaValue.trim()){
      message.open({
        type: 'warning',
        content: '请输入验证码',
        duration: 2.5,
      });
    }else if( captchaValue.toLowerCase() !== captchaText.toLowerCase()){
      message.open({
        type: 'warning',
        content: '验证码不正确',
        duration: 2.5,
      });
    }
    // 信息输入后进行登录操作
    else {
      let params = {
        username: usernameValue.trim(),
        password: pwdValue.trim(),
        captcha: captchaValue.trim(),
        captchaToken: localStorage.getItem('captchaToken') as string
      }
      // 调用仓库的login方法
      let loginRes = await clogin(params)
      if(loginRes == 200){
        // 跳转页面
        NavigateTo('/')
      }else{
          // 什么都不干
      }
    }
  }
  return (
    <div>
      <canvas id='canvas' style={{ display: 'block' }}></canvas>
      <div className={style.loginPage}>
        {/* 背景 */}

      
            {/* 登录盒子 */}
            <div className={style.loginBox + ' loginbox'}>
              {/* 标题 */}
              <div className={style.title}>
                <h1>理发店分销管理系统</h1>
              </div>
              {/* 表单 */}
              <form className='form' >
                <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                  <Input onChange={usernameChange} size="large" placeholder="用户名" autoComplete='on' prefix={<UserOutlined />} />
                  <Input.Password onChange={pwdChange} size="large" placeholder='密码' autoComplete='off' prefix={<LockOutlined />} />
                  <div className={style.verify}>
                    <Input onChange={captchaChange} size="large" placeholder='验证码' />
                    <div className={style.verify_img} onClick={upCaptcha}>
                      <div dangerouslySetInnerHTML={{ __html: captchaImg }} />
                    </div>
                  </div>
                  <Button onClick={loginBtn} size="large" type="primary" block>登录</Button>
                </Space>
              </form>
            </div>

      </div>
    </div>

  )
}
export default Login